package service

import (
	"e_mall_server/common"
	"e_mall_server/dao/mysql"
	"e_mall_server/models"
	"github.com/gin-gonic/gin"
)

/**
 * @Author: zhaobin
 * @Description TODO
 * @Date: 2022-05-20 12:41
 */

// GetOrderListByUserId 通过用户id获取订单列表接口
func GetOrderListByUserId(userId int64) ([]models.Order, error) {
	return mysql.GetOrderListByUserId(userId)
}

// GetOrderList 获取订单列表
func GetOrderList(orderPageParam *models.OrderPageParam) (orderResponse models.OrderResponse, err error) {
	// 对查询条件加工
	orderPageParam.Query = "%" + orderPageParam.Query + "%"

	// 查询总数量
	orderResponse.Total = mysql.GetOrderCount(orderPageParam)
	// 查询商品列表
	orderResponse.OrderList, err = mysql.GetOrderList(orderPageParam)
	return
}

// AddOrder 创建订单信息
func AddOrder(c *gin.Context, createOrderParam *models.CreateOrderParam) (string, error) {

	// 获取购买商品的信息
	goodsList := createOrderParam.GoodsList
	allPrice := createOrderParam.AllPrice
	// 获取用户的收货地址信息
	address := createOrderParam.Address
	// 获取用户id
	userId := createOrderParam.UserId

	// 减去数据库库存

	// 创建订单
	order := models.Order{
		OrderId:     common.GetOrderId(), // 使用雪花算法生成订单id
		UserId:      userId,
		AllPrice:    allPrice,
		Phone:       address.Phone,
		Name:        address.Name,
		Address:     address.Address,
		PayStatus:   0,
		PayType:     0,
		OrderStatus: 0,
	}
	if err := mysql.AddOrder(&order); err != nil {
		// 生成订单错误
		return "0", err
	}

	// 生成每一个订单项
	for i := 0; i < len(goodsList); i++ {
		orderItem := models.OrderItem{
			OrderId:    order.OrderId,
			UserId:     userId,
			GoodsTitle: goodsList[i].Title,
			GoodsId:    goodsList[i].Id,
			GoodsImg:   goodsList[i].GoodsImg,
			GoodsPrice: goodsList[i].Price,
			GoodsNum:   goodsList[i].Num,
		}
		// 创建订单项
		if err := mysql.AddOrderItem(&orderItem); err != nil {
			return "0", err
		}
	}

	// 删除购物车中选中数据
	var tempCartList []models.Cart
	models.Cookie.Get(c, models.CartList, &tempCartList)
	var cartList []models.Cart
	for i := 0; i < len(tempCartList); i++ {
		if tempCartList[i].Checked {
			cartList = append(cartList, tempCartList[i])
		}
	}
	return order.OrderId, nil
}

// GetOrderDetailById 通过id获取订单详细信息
func GetOrderDetailById(id int64) (models.Order, error) {
	return mysql.GetOrderDetailById(id)
}

// GetOrderByOrderId 通过订单id获取订单详细信息
func GetOrderByOrderId(orderId string) (models.Order, error) {
	return mysql.GetOrderByOrderId(orderId)
}

// UpdateOrder 修改订单信息
func UpdateOrder(Order *models.Order) int64 {
	return mysql.UpdateOrder(Order)
}

// DeleteOrderById 通过id删除订单数据
func DeleteOrderById(id int64) int64 {
	return mysql.DeleteOrderById(id)
}
